package main

import (
	"context"
	"flag"
	"fmt"
	"time"
	"github.com/coreos/etcd/clientv3"
)

func who_use_etcd() {
	etcdHost := flag.String("etcdHost", "127.0.0.1:2379", "etcd host")
	etcdWatchKey := "/vpp"
	flag.Parse()

	fmt.Println("connecting to etcd - " + *etcdHost)

	clientConfig := clientv3.Config{
			Endpoints:   []string{"http://" + *etcdHost},
				DialTimeout: 5 * time.Second,
	}
	etcd, err := clientv3.New(clientConfig)
	if err != nil {
		fmt.Println(err, "could not connect to etcd")
		return
	}

	defer etcd.Close()
	//https://blog.csdn.net/hello_ufo/article/details/89343957
	timeoutCtx, cancel := context.WithTimeout(context.Background(), 2 * time.Second)
	defer cancel()
	_, err = etcd.Status(timeoutCtx, clientConfig.Endpoints[0])
	if err != nil {
		fmt.Println("error checking etcd status: ", err)
		return
	}
	fmt.Println("connected to etcd - " + *etcdHost)
	watchChan := etcd.Watch(context.Background(), etcdWatchKey, clientv3.WithPrefix())
	fmt.Println("set WATCH on " + etcdWatchKey)
	for watchResp := range watchChan {
		for _, event := range watchResp.Events {
			client_connect_vpp(event)
		}
	}
}
